package com.ancient.config.datasource;

import java.sql.SQLException;
import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

@Configuration  
@MapperScan(basePackages = {"com.ancient.web.data1.dao"}, sqlSessionTemplateRef = "data1SqlSessionTemplate")
public class TestMyBatisConfig1 {
	
	@Autowired
	private DBConfig1 dBConfig1;
	
	@Primary  
    @Bean(name = "data1DataSource")  
	 public DataSource testDataSource(DBConfig1 testConfig) throws SQLException{
		HikariConfig hikariConfig = new HikariConfig();
		hikariConfig.setDriverClassName(dBConfig1.getMysqlDriver());
		hikariConfig.setJdbcUrl(dBConfig1.getMysqlUrl());
		hikariConfig.setUsername(dBConfig1.getMysqlUserName());
		hikariConfig.setPassword(dBConfig1.getMysqlPassword());
		hikariConfig.setMaximumPoolSize(5);
		hikariConfig.setConnectionTestQuery(dBConfig1.getMysqlConnectionTestQuery());
		hikariConfig.setPoolName("springHikariCP");
		hikariConfig.addDataSourceProperty("dataSource.cachePrepStmts", "true");
		hikariConfig.addDataSourceProperty("dataSource.prepStmtCacheSize", "250");
		hikariConfig.addDataSourceProperty("dataSource.prepStmtCacheSqlLimit", "2048");
		hikariConfig.addDataSourceProperty("dataSource.useServerPrepStmts", "true");
		HikariDataSource dataSource = new HikariDataSource(hikariConfig); 
        return dataSource; 
	 }
	 
	    @Bean(name = "data1SqlSessionFactory")  
	    @Primary 
	    public SqlSessionFactory testSqlSessionFactory(@Qualifier("data1DataSource") DataSource dataSource)throws Exception {  
	    	SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
			bean.setDataSource(dataSource);
			ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
			try { 
				bean.setMapperLocations(resolver.getResources("classpath*:mybatis/data1/*/*.xml"));
				return bean.getObject();
			} catch (Exception e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			}
	    }  
	  
	    @Bean(name = "data1SqlSessionTemplate")  
	    @Primary 
	    public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("data1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {  
	        return new SqlSessionTemplate(sqlSessionFactory);  
	    }  
}
